package com.yunxin.customui.service.adapter.table;

import cn.hutool.core.map.CaseInsensitiveMap;
import com.yunxin.customui.myinterface.table.ITableAdapter;
import com.yunxin.customui.bean.table.TableBean;
import com.yunxin.customui.bean.table.TdBean;
import com.yunxin.customui.bean.table.TrBean;
import com.yunxin.customui.bean.table.WebTableBean;
import com.yunxin.customui.bean.table.sqltable.TableSqlColumn;

import java.util.LinkedList;
import java.util.List;

/**
 * 表格对象适配器（临时用）
 *
 * @author LGY
 * @date 2021/09/27
 */
public class TableBySQLAdapter implements ITableAdapter<WebTableBean> {

    @Override
    public TableBean adaptation(WebTableBean webTableBean) {
        List datas = webTableBean.getDatas();
        List<TableSqlColumn> columns = webTableBean.getColumns();
        TableBean tableBean = new TableBean();
        //表头
        LinkedList thList = new LinkedList();
        TrBean thBean = new TrBean();
        int colNum = 0;
        for (TableSqlColumn column : columns) {
            TdBean td = new TdBean();
            td.setValue(column.getFieldDesc());
            td.setFieldName(column.getField());
            td.setCol(colNum++);
            thBean.getTdBeans().add(td);
        }
        thList.add(thBean);
        //数据
        LinkedList trList = new LinkedList();
        if (datas.size() > 0){
            int rowNum = 0;
            for (Object data : datas) {
                TrBean tr = new TrBean();
                CaseInsensitiveMap<String,String> rowDataMap = (CaseInsensitiveMap<String, String>) data;

                int trColNum = 0;
                for (TableSqlColumn col : columns) {
                    String colField = col.getField();
                    TdBean td = new TdBean();
                    td.setFieldName(col.getField());
                    String value = String.valueOf(rowDataMap.get(colField));
                    td.setValue(value);
                    td.setCol(trColNum);
                    td.setRow(rowNum);
                    //对共有配置写入td对象中
                    col.buildTdAttribute(td);
                    tr.getTdBeans().add(td);
                }
                trList.add(tr);
            }

        }

        tableBean.setThBeans(thList);
        tableBean.setTrBeans(trList);
        // 为了增加可选列
        tableBean.setColumns(columns);
        return tableBean;
    }
}
